<template>
  <page-header-wrapper>
    <a-card :bordered="false" v-if="excelStatus">
      <deliveries-excel @close="onExcelClose" @complete="onComplete" />
    </a-card>
    <a-card :bordered="false" v-if="!excelStatus">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <!-- :label-col="{xs: { span: 24 },sm: {span: 5}}" -->
              <!-- :wrapper-col="{xs: { span: 24 },sm: {span: 12}}" -->
              <a-form-item label="征订人">
                <a-input style="cursor:pointer;width: 100%;" @click="()=>{selectMemberVisible=true}" v-model="memberStr" placeholder=""/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="发行年份">
                <a-date-picker
                  mode="year"
                  format="YYYY"
                  style="width: 100%;"
                  v-model="queryParam.startDateRt"
                  placeholder=""
                  :open="yearPickerVisible"
                  @panelChange="onYearPickerPanelChange"
                  @openChange="onYearPickerOpenChange"
                  @change="onYearPickerChange"
                />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="this.resetForm">重置</a-button>
              </span>
            </a-col>
          </a-row>
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="详细地址">
                <a-input v-model="queryParam.search" style="width: 100%;" placeholder=""/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="报刊种类" :wrapperCol="wrapperCol" style="overflow: hidden;">
                <a-select @change="subscriptionTypeChange" style="width: 100%;">
                  <a-select-option v-for="(item, index) in recordSettingList" :key="index">
                    {{ item.title }}
                  </a-select-option>
                </a-select>
                <!-- <a-input v-model="queryParam.subscriptionType" placeholder=""/> -->
              </a-form-item>
            </a-col>
            <!-- <a-col :md="8" :sm="24"> -->
            <!-- </a-col> -->
          </a-row>
          <a-row :gutter="48">
            <a-col span="8">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" icon="plus" @click="toAdd">新增</a-button>
                <a-button style="margin-left: 16px;" type="primary" @click="toExcel">Excel导入</a-button>
                <a-button style="margin-left: 8px" type="primary" @click="exportExcel">导出Excel</a-button>
                <!-- <a-button :loading="syncFlag" style="margin-left: 16px;" type="primary" @click="toSyncData">同步投递信息（大约30分钟）</a-button> -->
              </span>
            </a-col>
            <a-col span="2">
              <span class="table-page-search-submitButtons">
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <s-table
        ref="table"
        :columns="columns"
        :data="loadData"
        :row-key="(record)=>record.id"
        :showPagination="true"
      >
        <span slot="submitState" slot-scope="text, record">
          <a-dropdown style="cursor: pointer; !important">
            <a-tag :color="(text === '待审核') ? 'orange' : (text === '待开票') ? 'blue' : (text === '待发行') ? 'purple' : 'green'">
              {{ text }}
            </a-tag>
            <a-menu slot="overlay">
              <a-menu-item key="待审核" style="cursor:pointer;">
                <a href="javascript:;" @click="updateState(record, '待审核')">待审核</a>
              </a-menu-item>
              <a-menu-item key="待开票" style="cursor:pointer;">
                <a href="javascript:;" @click="updateState(record, '待开票')">待开票</a>
              </a-menu-item>
              <a-menu-item key="待发行" style="cursor:pointer;">
                <a href="javascript:;" @click="updateState(record, '待发行')">待发行</a>
              </a-menu-item>
              <a-menu-item key="已完成" style="cursor:pointer;">
                <a href="javascript:;" @click="updateState(record, '已完成')">已完成</a>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
        <span slot="code" slot-scope="text">
          <img :src="text" style="width:80px;height:80px;" />
        </span>
        <span slot="action" slot-scope="text, record">
          <template>
            <a @click="toTicketDetail(record)">
              <a-icon type="money-collect"></a-icon>
              查看发票
            </a>
            <a @click="toBandTicket(record)">
              <a-icon type="money-collect"></a-icon>
              绑定发票
            </a>
            <a-divider type="vertical" />
            <a @click="toDetailOnly(record)">详情</a>
            <a-divider type="vertical" />
            <a @click="toDetail(record)">编辑</a>
            <a-divider type="vertical" />
            <a-popconfirm placement="topLeft" ok-text="是" cancel-text="否" @confirm="toDelete(record)">
              <template slot="title">
                <p>确定要删除这条记录吗？</p>
              </template>
              <!-- <a-button>TL</a-button> -->
              <a>删除</a>
            </a-popconfirm>
          </template>
        </span>
      </s-table>
      <detail-form :visible="detailVisible" :model="this.model" @cancel="()=>{this.detailVisible=false}" @ok="modalOk" />
      <band-ticket :visible="bandTickVisible" :model="this.model" @cancel="()=>{this.bandTickVisible=false}" @ok="modalOk" />
      <ticket-detail :visible="ticketDetailVisible" :model="this.model" @cancel="()=>{this.ticketDetailVisible=false}" @ok="modalOk" />
      <detail-only :visible="detailOnlyVisible" :model="this.model" @cancel="()=>{this.detailOnlyVisible=false}" @ok="modalOk" />
      <select-member @OnSelect="onMemberSelect" :visible="selectMemberVisible" :model="this.model" @cancel="()=>{this.selectMemberVisible=false}" @ok="modalOk" />
    </a-card>
  </page-header-wrapper>
</template>

<script>

// import XLSXS from 'xlsx-style'
import XLSX from 'xlsx'
import { getSettingLists, getDeliveriesLists, deleteDeliveries, putDeliveries, syncOrder } from '@/api/manage'
import { STable } from '@/components'
import DetailForm from './Detail'
import BandTicket from './BandTicket'
import { notification } from 'ant-design-vue'
import TicketDetail from './TicketDetail'
import DetailOnly from './DetailOnly'
import DeliveriesExcel from './DeliveriesExcel'
import SelectMember from './SelectMember'
// require('script-loader!file-saver')
require('xlsx-style')
export default {
  name: 'DeliveryLists',
  data () {
    return {
      wrapperCol: {
        xs: { span: 24 },
        sm: { flex: 1 }
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      memberStr: '',
      recordSettingList: [],
      selectMemberVisible: false,
      yearPickerVisible: false,
      excelStatus: false,
      model: {},
      syncFlag: false,
      detailOnlyVisible: false,
      bandTickVisible: false,
      detailVisible: false,
      ticketDetailVisible: false,
      queryParam: {},
      departmentList: [],
      columns: [
        {
          title: '#',
          dataIndex: 'id'
        },
        {
          title: '关联人员',
          dataIndex: 'member.name'
        },
        {
          title: '关联客户',
          dataIndex: 'customerName'
        },
        {
          title: '订单类型',
          dataIndex: 'orderType'
        },
        {
          title: '收订员',
          dataIndex: 'subScriptioner'
        },
        {
          title: '份数',
          dataIndex: 'subscriptionCount'
        },
        {
          title: '报刊种类',
          dataIndex: 'pressTypeStr'
        },
        {
          title: '订阅类型',
          dataIndex: 'subscriptionType'
        },
        {
          title: '状态',
          dataIndex: 'submitState',
          scopedSlots: { customRender: 'submitState' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '350px',
          scopedSlots: { customRender: 'action' }
        }
      ],
      loadData: parameter => {
        // 不要在这里修改分页大小，STable已经写死默认每一页10条
        const cParameter = { pageSize: parameter.pageSize, pageNum: parameter.pageNo }
        const requestParameter = Object.assign({}, cParameter, this.queryParam)
        return new Promise((resolve, reject) => {
          getDeliveriesLists(requestParameter).then(res => {
            getSettingLists().then(settingRes => {
              this.recordSettingList = settingRes.data
              this.departmentList = res.data
              res.data.forEach((item) => {
                for (let index = 0; index < settingRes.data.length; index++) {
                  const settingItem = settingRes.data[index]
                  console.log(typeof item.pressType)
                  console.log(settingItem.id)
                  if (parseInt(item.pressType) === settingItem.id) item.pressTypeStr = settingItem.title
                }
                item.startDate = this.Format(item.startDate, 'yyyy-MM-dd hh:mm:ss')
                item.endDate = this.Format(item.endDate, 'yyyy-MM-dd hh:mm:ss')
              })
              console.log(res.data)
              resolve({
                data: res.data,
                totalCount: parseInt(res.headers['x-count']),
                pageNo: parameter.pageNo,
                pageSize: parameter.pageSize
              })
            })
            // return {
            //   data: res.data,
            //   totalCount: parseInt(res.headers['x-count']),
            //   pageNo: parameter.pageNo,
            //   pageSize: parameter.pageSize
            // }
          })
        })
        // return getDeliveriesLists(requestParameter).then(res => {
        //   await getSettingLists().then(settingRes => {
        //     this.recordSettingList = res.data
        //     this.departmentList = res.data
        //     res.data.forEach((item) => {
        //       await settingRes.data.forEach((_item) => {
        //         if (item.pressType === _item.id) item.pressTypeStr = settingItem.title
        //       })
        //       item.startDate = this.Format(item.startDate, 'yyyy-MM-dd hh:mm:ss')
        //       item.endDate = this.Format(item.endDate, 'yyyy-MM-dd hh:mm:ss')
        //     })
        //   })
        //   return {
        //     data: res.data,
        //     totalCount: parseInt(res.headers['x-count']),
        //     pageNo: parameter.pageNo,
        //     pageSize: parameter.pageSize
        //   }
        // })
      }
    }
  },
  components: {
    STable,
    DetailForm,
    BandTicket,
    TicketDetail,
    DetailOnly,
    DeliveriesExcel,
    SelectMember
  },
  created () {
    // this.init()
  },
  methods: {
    resetForm () {
      this.queryParam = {}
      this.$form.resetFields()
    },
    onMemberSelect (v) {
      this.memberStr = v.name
      this.queryParam.memberId = v.id
      this.selectMemberVisible = false
    },
    subscriptionTypeChange (v) {
      this.queryParam.subscriptionType = v
    },
    onYearPickerPanelChange (v) {
      this.queryParam.startDateRt = v.format('YYYY') + '-01-01' // 由于后端接口原因，所以需要明确到月份以及日期
      this.yearPickerVisible = false
    },
    onYearPickerOpenChange (status) {
      this.yearPickerVisible = status
    },
    onYearPickerChange () {
      // this.queryParam.startDateRt = null
    },
    exportExcel () {
      const aoa = []
      const tableHeader = []
      this.columns.forEach((item, index) => {
        tableHeader.push(item.title)
      })
      // 表头数据添加
      aoa.push(tableHeader)
      // 表格数据添加
      const tableData = this.departmentList.map((item, index) => {
        const result = []
        this.columns.forEach(c => {
          result.push((c.title === '#') ? index + 1 : item[c.dataIndex])
          // result[c.dataIndex] = (c.title === '#') ? index + 1 : item[c.dataIndex]
        })
        aoa.push(result)
        return result
      })
      console.log(tableData)
      // aoa.push(tableData)
      // 导出的表格名称
      const filename = '导出表格.xlsx'
      // Excel第一个sheet的名称
      const wsName = 'Sheet1'
      const wb = XLSX.utils.book_new()
      const ws = XLSX.utils.aoa_to_sheet(aoa)
      console.log(ws)
      // ws['!rows'].s={
      //   font: {
      //     sz: 13,
      //     bold: true,
      //     color: {
      //       rgb: 'FFFFAA00'
      //     }
      //   },
      //   alignment: {
      //     horizontal: 'center',
      //     vertical: 'center',
      //     wrap_text: true
      //   }
      // }
      const style0 = { alignment: { horizontal: 'center', wrapText: true, vertical: 'center' }, font: { sz: 18, bold: true, color: { rgb: '000000' }, outline: true } }
      ws['A1'].s = style0
      // ws['A1'].s = {
      //   font: {
      //     sz: 13,
      //     bold: true,
      //     color: {
      //       rgb: 'FFFFAA00'
      //     }
      //   },
      //   alignment: {
      //     horizontal: 'center',
      //     vertical: 'center',
      //     wrap_text: true
      //   }
      // }
      ws['!cols'] = [
        {
          wpx: 170
        }, {
          wpx: 70
        }, {
          wpx: 70
        }, {
          wpx: 70
        }, {
          wpx: 150
        }, {
          wpx: 120
        }
      ]
      XLSX.utils.book_append_sheet(wb, ws, wsName) // 将数据添加到工作薄
      XLSX.writeFile(wb, filename) // 导出Excel
    },
    onComplete () {
      this.excelStatus = false
      notification.success({
        message: '提示',
        description: '数据导入成功！'
      })
      this.$refs.table.refresh(true)
    },
    onExcelClose () {
      this.excelStatus = false
    },
    toExcel () {
      this.excelStatus = true
    },
    toSyncData () {
      if (this.syncFlag) return
      const _selft = this
      this.$confirm({
        title: '提示',
        content: '确定开始同步投递信息数据吗？此过程大约需要30分钟！',
        onOk () {
          _selft.syncFlag = true
          _selft.$message.success('投递信息数据已开始同步（大约需要30分钟）！')
          notification.success({
            message: '提示',
            description: '投递信息数据已经开始同步（大约需要30分钟），请勿重复点击！'
          })
          const sT = setTimeout(() => {
            _selft.syncFlag = false
          }, 30 * 1000 * 60)
          syncOrder().then(res => {
            _selft.$message.success('投递信息数据同步完成！')
            notification.success({
              message: '提示',
              description: '投递信息数据同步完成！'
            })
            _selft.queryParam = {}
            _selft.$refs.table.refresh(true)
          }).catch(e => {
            _selft.$message.error('同步投递信息数据出错！')
            notification.error({
              message: '提示',
              description: '同步投递信息数据出错！'
            })
            clearTimeout(sT)
            _selft.syncFlag = false
          })
        },
        onCancel () {}
      })
    },
    updateState (record, state) {
      const tempState = { ...record }
      tempState.submitState = state
      putDeliveries(tempState.id, tempState).then(res => {
        this.$refs.table.refresh(true)
      })
    },
    toDetailOnly (record) {
      this.model = record
      this.detailOnlyVisible = true
    },
    toTicketDetail (record) {
      this.model = record
      this.ticketDetailVisible = true
    },
    modalOk () {
      this.model = {}
      this.selectMemberVisible = false
      this.detailVisible = false
      this.bandTickVisible = false
      this.$refs.table.refresh(false)
    },
    init () {
      getDeliveriesLists({ pageSize: this.pageSize, pageNum: this.pageNo }).then(res => {
        this.departmentList = res.data
        console.log(this.departmentList)
      })
    },
    toAdd () {
      this.model = {}
      this.detailVisible = true
    },
    toBandTicket (record) {
      this.model = record
      this.bandTickVisible = true
    },
    toDetail (record) {
      this.model = record
      this.detailVisible = true
    },
    toDelete (record) {
      deleteDeliveries(record.id).then(res => {
        notification.success({
          message: '提示',
          description: '删除成功'
        })
        this.$refs.table.refresh(false)
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
